<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, reactive, ref, watch } from 'vue'
import * as echarts from 'echarts'
import { DEFAULT_ECHARTS_FONTSIZE,DIALOG_ECHARTS_FONTSIZE } from '@/Utils/setting'
import { useDialogStore } from '@/stores/dialog'
const dialogStore = useDialogStore()
const { dialogInfo } = dialogStore


const fontSize = dialogInfo.visible ? DIALOG_ECHARTS_FONTSIZE : DEFAULT_ECHARTS_FONTSIZE
const dialogInfoVisible = dialogInfo.visible

// 调整px到合适的大小
const changePixelSize = (px: number) => {
  // 获取当前屏幕宽度
  const width = document.body.clientWidth
  let res = (px / 1920) * width
  // 保留整数
  return parseInt(res.toFixed(0))
}
const props = defineProps<{
  chartData: any
}>()
props.chartData.name = props.chartData.name + Math.random()


let option = null

let myChart: echarts.ECharts
const createChart = () => {
  // 判断是否能获取到dom,如果不能直接结束
  const theDom = document.getElementById(props.chartData.name)
  if (!theDom) {
    return ''
  }
  myChart = echarts.init(document.getElementById(props.chartData.name))

  const colors = ['#5470C6', '#91CC75', '#EE6666']

  option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        crossStyle: {
          color: '#999',
        },
      },
      textStyle: {
        fontSize: changePixelSize(fontSize),
        color: '#fff',
      },
      position: ['25%', '50%'],
      padding: [
        changePixelSize(10), // 上
        changePixelSize(10), // 右
        changePixelSize(10), // 下
        changePixelSize(10), // 左
      ],
      backgroundColor: 'rgba(0,0,0,0.7)',
    },
    color: ['#EB6456', '##EB6456', '#EE6666'], // 设置折线颜色
    legend: [
      {
        data:
          [
            props.chartData?.data[0]?.bar?.name || '',
            props.chartData?.data[0]?.line?.name || '',
          ].length > 1
            ? [
                props.chartData?.data[0]?.bar?.name || '',
                props.chartData?.data[0]?.line?.name || '',
              ]
            : [],
        itemWidth: changePixelSize(20.2),
        itemHeight: changePixelSize(10.5),
        textStyle: {
          fontSize: changePixelSize(fontSize),
          lineHeight: changePixelSize(15),
          color: '#fff',
        },
      },
    ],
    grid: {
      left: '5%',
      right: '5%',
      top: '13%',
      bottom: '10%',
      containLabel: true, // 是否居中显示图表
    },
    xAxis: [
      {
        type: 'category',
        data: props.chartData?.xAxis.data,
        axisTick: {
          show: false, // 关闭刻度线
        },
        axisLine: {
          show: false, // 关闭轴线
        },
        axisLabel: {
          color: '#fff', // 设置 X 轴标签字体颜色
          interval: 0, // 强制显示所有标签
          fontSize: changePixelSize(fontSize),
          // margin: changePixelSize(5), // 调整标签与轴线的距离
          formatter:dialogInfoVisible==false? function (str: any) {
            // 中文算2,英文算1,数到maxLength截取,然后打...
            let count = 0
            let result = ''

            for (let i = 0; i < str.length; i++) {
              const char = str.charAt(i)
              count += /[\u4E00-\u9FA5]/g.test(char) ? 2 : 1

              if (count > 8) {
                result += '...'
                break
              }

              result += char
            }
            return result
          }:function (str: any) {
            // 中文算2,英文算1,数到maxLength截取,然后打...
            let count = 0
            let result = ''

            for (let i = 0; i < str.length; i++) {
              const char = str.charAt(i)
              count += /[\u4E00-\u9FA5]/g.test(char) ? 2 : 1

              if (count > 10) {
                result += '...'
                break
              }

              result += char
            }
            return result
          },
        },
      },
    ],
    yAxis: [
      {
        type: 'value',
        axisLabel: {
          fontSize: changePixelSize(fontSize),
          color: '#08ffff',
          margin: changePixelSize(5), // 调整标签与轴线的距离
        },
        splitLine: {
          lineStyle: {
            color: '#123545', // 分割线颜色为灰色
          },
        },
      },
      {
        type: 'value',
        splitLine: {
          lineStyle: {
            color: '#123545', // 分割线颜色为灰色
          },
        },
        axisLabel: {
          fontSize: changePixelSize(fontSize),
          color: '#08ffff',
          margin: changePixelSize(5), // 调整标签与轴线的距离
          formatter: function (params) {
            return params + '%'
          },
        },
      },
    ],
    dataZoom: [
      {
        type: 'inside',
        show: false,
        xAxisIndex: [0],
        zoomOnMouseWheel: false, // 禁止鼠标滚轮缩放
        moveOnMouseWheel: true, // 开启鼠标滚轮窗口平移
        moveOnMouseMove: true, // 开启鼠标移动窗口平移
        throttle: 100, // 限制滑动的频率，单位为毫秒
        start: 0,
        end:
          props.chartData?.xAxis.data.length > 3
            ? ~~((3 / props.chartData?.xAxis.data.length) * 100)
            : 100,

        showDataShadow: false,

        textStyle: {
          color: '#ccd7d7',
        },
      },
    ],
    series:
      // series[0],
      [
        {
          name: props.chartData?.data[0]?.bar?.name || '',
          type: 'bar',
          barWidth: changePixelSize(20), // 设置柱状图的宽度
          data: props.chartData?.data[0]?.bar?.value,
          itemStyle: {
            color: props.chartData?.barShiny
              ? new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: '#68E0CF' },
                  { offset: 1, color: '#529BED' },
                ])
              : new echarts.graphic.LinearGradient(0, 1, 0, 0, [
                  { offset: 0, color: '#7C73F3' },
                  { offset: 1, color: '#529BED' },
                ]),
          },
        },
        {
          name: props.chartData?.data[0]?.line?.name || '',
          type: 'line',
          yAxisIndex: 1,
          symbol: 'circle', //将小圆点改成实心 不写symbol默认空心
          symbolSize: 5, //小圆点的大小
          data: props.chartData?.data[0]?.line?.value || '',
          tooltip: {
            valueFormatter: function (value) {
              return value + ' %'
            },
          },
        },
      ],
  }
  // 绘制图表
  myChart.setOption(option)
}

onMounted(() => {
  nextTick(() => {
    createChart()
  })
})
// 销毁前释放内存
onBeforeUnmount(() => {
  if (myChart) {
    myChart.dispose()
  }
})
watch(
  () => props.chartData,
  () => {
    nextTick(() => {
      createChart()
    })
  },
  { deep: true }
)
</script>

<template>
  <div
    :class="{
      'echart-box': true,
      'dialog-box': dialogInfoVisible == true,
    }"
  >
      <div class="sub-title" v-if="chartData?.subTitle">
      {{ chartData.subTitle }}
      <span>{{ chartData.subTitleVal }}</span>
    </div>
    <div class="chart" :id="chartData.name"></div>
  </div>
</template>

<style lang="scss" scoped>
.echart-box {
  position: relative;
  width: 100%;
  height: calc(260px); // 10px是指示器高度
  display: flex;
  flex-direction: column;
  .chart {
    width: 100%;
    flex: 1;
  }
  .sub-title {
    padding: 10px;
    font-size: 12px;
    span {
      color: #eb6456;
    }
  }
}
.dialog-box {
  height: calc(
    500px - 45px
  );
}
</style>
